#include <iostream>

#include <cstring>

#include <unistd.h>
#include <fcntl.h>

void set_no_block(int fd)
{
    int f = fcntl(fd, F_GETFL);
    if (f < 0)
        exit(-1);
    else
        fcntl(fd, F_SETFL, f | O_NONBLOCK);
    std::cout << "set " << fd << " no block" << std::endl;
}

int main()
{
    set_no_block(0);

    char buffer[128] = { 0 };
    while (true)
    {
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n - 1] = '\0';
            std::cout << "echo: " << buffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "read done" << std::endl;
            break;
        }
        else
        {
            if (errno == EWOULDBLOCK)
                std::cout << "0 fd data" << std::endl;
            else
                std::cerr << "read error, n = " << n << " errno: " << errno << " error string: " << strerror(errno) << std::endl;
            sleep(1);
        }
    }
    return 0;
}